package com.dacool.fragment;

import static com.dacool.util.ViewUtils.rp;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

import com.dacool.activity.BaseActivity;
import com.dacool.app.sale.R;
import com.dacool.config.Config;
import com.dacool.http.BaseRequest;
import com.dacool.http.BaseRequest.ResponseHandler;
import com.dacool.http.GetBannerRequest;
import com.dacool.model.DacoolProduct;
import com.dacool.util.ViewUtils;
import com.dacool.view.CirclePageIndicator;
import com.dacool.view.IconView;
import com.dacool.view.MyImageViewPager;
import com.dacool.view.MyImageViewPager.MyViewPagerDelegate;

public class HomeFragment extends BaseFragment implements MyViewPagerDelegate {
	private MyImageViewPager mBanner;
	private CirclePageIndicator mPageIndicator;
	private MyImageViewPager mBanner1;
//	private IconView icon1;
//	private IconView icon2;
//	private IconView icon3;
//	private IconView icon4;

	private ArrayList<DacoolProduct> products = new ArrayList<DacoolProduct>();

	@Override
	protected View myView() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected int myLayoutID() {
		// TODO Auto-generated method stub
		return R.layout.frag_home;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rl = super.onCreateView(inflater, container, savedInstanceState);
		mBanner = (MyImageViewPager) rl.findViewById(R.id.viewPager);
//		ArrayList<Integer> ids = new ArrayList<Integer>();
//		ids.add(R.drawable.bannerimg);
//		mBanner.setDrawableIDs(ids);
		mPageIndicator = (CirclePageIndicator) rl.findViewById(R.id.indicator);
		mPageIndicator.setCount(mBanner.getRealCount());
		mPageIndicator.setFillColor(0xff85c400);
		mPageIndicator.setPageColor(0xff888888);
		mPageIndicator.setStrokeWidth(0);
		mPageIndicator.setRadius(rp(5));
		mBanner.setDelegate(this);
		mBanner.setScrollInterval(5000);
		mBanner.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int pos) {
				int realPos = ((pos - 500) % mBanner.getRealCount() + mBanner
						.getRealCount()) % mBanner.getRealCount();
				mPageIndicator.setCurrentItem(realPos);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});

		mBanner1 = (MyImageViewPager) rl.findViewById(R.id.viewPager1);
		mBanner1.setScrollInterval(10000);
		ArrayList<Integer> ids = new ArrayList<Integer>();
		ids.add(R.drawable.bottom_pannel_img1);
		ids.add(R.drawable.bottom_pannel_img2);
		ids.add(R.drawable.bottom_pannel_img3);
		mBanner1.setDrawableIDs(ids);
//		icon1 = (IconView) rl.findViewById(R.id.icon1);
//		icon2 = (IconView) rl.findViewById(R.id.icon2);
//		icon3 = (IconView) rl.findViewById(R.id.icon3);
//		icon4 = (IconView) rl.findViewById(R.id.icon4);
//
//		icon1.setText("热门搜索");
//		icon2.setText("热销商品");
//		icon3.setText("订单评价");
//		icon4.setText("我   库");

//		icon1.setOnClickListener(this);
//		icon2.setOnClickListener(this);
////		icon3.setOnClickListener(this);
//		icon4.setOnClickListener(this);
		// mPageIndicator.setViewPager(mBanner);
		return rl;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
//		if (icon2 == v) {
//			getContainerActivity().getMainActivity().setCurrentTab(2,
//					ProductListFragment.class);
//			// ProductListFragment fragment = new ProductListFragment();
//			// getContainerActivity().addFragment(fragment);
//		} else if (icon4 == v) {
//			((BaseActivity) getActivity()).getMainActivity().setCurrentTab(4);
//		}
		super.onClick(v);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		this.loadBanners();
	}

	private void loadBanners() {
		/**
		 * { "focusImg": [ 
		 * 　　{ "imgName": "xxx", "imgUrl":"/1/2/1.jpg", "linkurl": "链接到那个页面" }, 
		 * 　　{"imgName": "xxx", "imgUrl":"/1/2/1.jpg", "linkurl": "链接到那个页面"}, 
		 * 　　{ "imgName": "xxx", "imgUrl":"/1/2/1.jpg", "linkurl": "链接到那个页面"} 
		 * 　　]} 
		 */
		new GetBannerRequest().setType("0").setHandler(new ResponseHandler() {

			@Override
			public void handleResponse(BaseRequest request, int statusCode,
					String errorMsg, String response) {
				if (statusCode != 200)
					return;
				boolean success = false;
				try {
					JSONObject object = new JSONObject(response);
					success = object.optBoolean("success", false);

					JSONArray array = object.getJSONArray("data");
					products = new ArrayList<DacoolProduct>();
					for (int i = 0; i < array.length(); i++) {
						JSONObject obj = array.getJSONObject(i);
						DacoolProduct product = new DacoolProduct();
						product.setName(obj.getString("name"));
						product.setDescription(obj.getString("brief"));
						// XXX price should be double already!!!
						product.setPrice(obj.getDouble("price"));
						product.setId(obj.getString("goodsId"));
						String url = obj.getString("smallPic");
						product.setIconUrl(url);
						JSONArray arr = obj.optJSONArray("bigPics");
						ArrayList<String> urls = new ArrayList<String>();
						if (arr != null)
							for (int j = 0; j < arr.length(); j++) {
								urls.add(arr.getString(j));
							}
						product.setImageUrls(urls);
						url = obj.getString("thumbnailPic");
						product.setThumbnailImageUrl(url);
						products.add(product);
					}
					ViewUtils.runInMainThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							ArrayList<String> urls = new ArrayList<String>();
							for(DacoolProduct product : products){
								if(product.getImageUrls().size()>0){
									urls.add(product.getImageUrls().get(0));
								}
							}
							mBanner.setImageUrls(urls);
							mPageIndicator.setCount(mBanner.getRealCount());
						}
					});
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}).start();
	}

	@Override
	public void didTapAtView() {

		int index = mPageIndicator.getCurrentItem();
//		Log.d("test", "did tap at index:" + index);
		if (index < products.size() && index >= 0) {
			DacoolProduct product = products.get(index);
			if(product.getId()==null)
				return;
			else{
				try{
					long id = Long.parseLong(product.getId());
					if(id>0){
						ProductInfoFragment fragment = new ProductInfoFragment();
						fragment.setProduct(product);
						getContainerActivity().addFragment(fragment);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
}
